# this is the entity for store online

from google.appengine.ext import db
from datetime import datetime
from datetime import timedelta

class Data(db.Model):
  uuid = db.StringProperty()
  content = db.TextProperty()
  datetime = db.DateTimeProperty()
  
  def __str__(self,tzoffset):
    s = "{"
    s = s + "'id':'" + self.uuid + "',"
    s = s + "'ct':'" + jsonStringSpecialHandler(self.content) +"',"
    s = s + "'dt':'" + formatDateTime(self.datetime,tzoffset) + "'"
    s = s + "}"
    return s.encode("utf-8")
    
  

class Segment(db.Model):
  uuid = db.StringProperty()
  seq  = db.IntegerProperty()
  content = db.TextProperty()
  datetime = db.DateTimeProperty()
  
  def __str__(self):
    s = ""
    s = s + "uuid: "+ self.uuid
    s = s + ", seq: "+ str(self.seq)
    s = s + ", content: "+ jsonStringSpecialHandler(self.content)
    s = s + ", datetime: "+ str(self.datetime)
    return s.encode("utf-8")



# special handle for json, like ",'
def jsonStringSpecialHandler(str):
  return str.replace("\"","\\\"").replace("'","\\'").replace("\n","\\n");
  
# if year is different, show yyyy.mmm.dd
# if month different, show mmm.dd
# if day different, show mmm.dd HH:MM
# else HH:MM
def formatDateTime(dt,tzoffset):
  if dt is None:
    return "None"
  
  if tzoffset is not None:
    td = timedelta(seconds=int(tzoffset))
    dt = dt - td
  
  now = datetime.now()
  if dt.year != now.year:
    return dt.strftime("%Y.") + monthNameList[dt.month] + dt.strftime(".%d")
  elif dt.month != now.month:
    return monthNameList[dt.month] + dt.strftime(".%d")
  elif dt.day != now.day:
    return monthNameList[dt.month] + dt.strftime(".%d") + dt.strftime(" %H:%M")
  else:
    return dt.strftime("%H:%M")
  
  
monthNameList = ["","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
